<template>
  <div id="listSettings">
    <el-button v-if="showBtn" plain type="single-number" @click="handleClick">
      {{ btnText }}
    </el-button>
    <el-dialog
      v-if="showDialogVisible"
      width="40%"
      :title="dialogTitle"
      :visible.sync="showDialogVisible"
      destroy-on-close
      custom-class="revenue-code-number"
      :before-close="cance"
    >
      <div class="el-dialog__body-bodys">
        <el-form
          :model="form"
          ref="form"
          label-width="144px"
          class="ccui-form"
          :rules="rules"
        >
          <!-- v-if="!getMultiRateCode && status === 'outside'" -->
          <el-form-item
            v-if="['taxRate'].includes(status)"
            label="税率："
            prop="taxRatePercent"
          >
            <el-select
              class="ccui-form-longInput"
              v-model="form.taxRatePercent"
              placeholder="请选择"
              @change="taxRateChange"
            >
              <el-option
                v-for="item in Enum.taxRateList"
                :key="item.dicKey"
                :label="item.dicValue"
                :value="item.dicValue"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            v-if="['address', 'rowAddress'].includes(status)"
            :label="`${addressLabel}：`"
            required
          >
            <el-select
              class="area-select"
              v-model="form.deliveryAreaName"
              placeholder="请选择地区"
              @change="handleChange('deliveryArea')"
            >
              <el-option
                v-for="item in deliveryAreaOptions"
                :key="item.addressCode"
                :label="item.addressAbbr"
                :value="item.addressAbbr"
              >
              </el-option>
            </el-select>
            <el-select
              class="area-select"
              v-model="form.provinceName"
              placeholder="请选择省份"
              @change="handleChange('province')"
            >
              <el-option
                v-for="item in provinceOptions"
                :key="item.addressCode"
                :label="item.addressAbbr"
                :value="item.addressAbbr"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            v-if="['address', 'rowAddress'].includes(status)"
            label=""
          >
            <el-select
              class="area-select"
              v-model="form.cityName"
              placeholder="请选择市"
              @change="handleChange('city')"
            >
              <el-option
                v-for="item in cityOptions"
                :key="item.addressCode"
                :label="item.addressAbbr"
                :value="item.addressAbbr"
              >
              </el-option>
            </el-select>
            <el-select
              class="area-select"
              v-model="form.countyName"
              placeholder="请选择县"
              @change="handleChange('county')"
            >
              <el-option
                v-for="item in countyOptions"
                :key="item.addressCode"
                :label="item.addressAbbr"
                :value="item.addressAbbr"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            v-if="['address', 'rowAddress'].includes(status)"
            label=""
          >
            <el-input
              v-model="form.deliveryPoints"
              placeholder="请输入详细地址"
              maxlength="200"
            />
          </el-form-item>

          <el-form-item
            v-if="status === 'deliveryTime'"
            label="交货时间："
            prop="deliveryTime"
          >
            <el-date-picker
              v-model="form.deliveryTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>

          <el-form-item
            v-if="status === 'manufacturer'"
            label="交货厂家/品牌："
            prop="manufacturer"
          >
            <el-input
              type="textarea"
              placeholder="请输入交货厂家/品牌"
              v-model="form.manufacturer"
              show-word-limit
              style="min-height: 90px"
              resize="none"
              maxlength="200"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="default-mini" @click="cance"
          >取 消</el-button
        >
        <el-button size="mini" type="primary-font-mini" @click="confirmSend"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getQryAreaAddress, postGetEnum } from "@/basa/api";
export default {
  name: "listSettings",
  components: {},
  props: {
    addressLabel: {
      type: String,
      default: "交货地点"
    },
    showBtn: {
      type: Boolean,
      default: false
    },
    isSelect: {
      type: Boolean,
      default: false
    },
    btnText: {
      type: String,
      default: ""
    },
    dialogTitle: {
      type: String,
      default: ""
    },
    status: {
      type: String,
      default: ""
    },
    detail: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      showDialogVisible: false,
      form: {},
      rules: {
        deliveryAreaName: [
          { required: true, message: "请选择交货地点", trigger: "change" }
        ]
      },
      Enum: {
        taxRateList: []
      },
      deliveryAreaOptions: [],
      provinceOptions: [],
      cityOptions: [],
      countyOptions: [],
      areaArr: ["deliveryArea", "province", "city", "county"]
    };
  },
  created() {
    this.postGetEnum();
  },
  methods: {
    init() {
      this.form = this.detail;
      this.getQryAreaAddress();
      // 省
      this.getQryAreaAddress(this.detail.deliveryAreaCode);
      // 市
      this.getQryAreaAddress(this.detail.province, "province");
      // 区
      this.getQryAreaAddress(this.detail.city, "city");
    },
    cance() {
      this.showDialogVisible = false;
      this.$emit("cancesite");
    },

    // 获取枚举
    postGetEnum() {
      const arr = [
        "getTaxRateDict" // 查询税率字典数据
      ];
      for (let i = 0; i < arr.length; i++) {
        const element = arr[i];
        postGetEnum(element).then(res => {
          this.Enum[Object.keys(this.Enum)[i]] = res.data.data;
        });
      }
    },

    handleClick() {
      if (!this.isSelect) {
        return this.$showErrorMessage("未选中复选框");
      }
      this.showDialogVisible = true;
      this.getQryAreaAddress();
    },

    taxRateChange(val) {
      this.form.taxRateCode = this.Enum.taxRateList.find(
        _ => _.dicValue === val
      ).dicKey;
    },

    handleChange(type) {
      const tempCode = this[`${type}Options`].find(
        _ => _.addressAbbr === this.form[`${type}Name`]
      ).addressCode;

      if (type === "deliveryArea") {
        this.form[`${type}Code`] = tempCode;
        this.form.provinceName = "";
        this.form.cityName = "";
        this.form.countyName = "";
        this.cityOptions = [];
        this.countyOptions = [];
      } else {
        this.form[`${type}`] = tempCode;
      }

      if (type === "province") {
        this.form.cityName = "";
        this.form.countyName = "";
        this.countyOptions = [];
      }
      if (type === "city") {
        this.form.countyName = "";
      }
      this.$forceUpdate();

      if (type !== "county") {
        this.getQryAreaAddress(tempCode, type);
      }
    },

    getQryAreaAddress(parentCode = null, branch = "deliveryArea") {
      const data = { parentCode, overseasFlag: 0 };
      getQryAreaAddress(data).then(res => {
        if (res.data.code === "0") {
          if (parentCode == null) {
            this.deliveryAreaOptions = res.data.data;
          } else {
            this[
              `${
                this.areaArr[this.areaArr.findIndex(_ => _ === branch) + 1]
              }Options`
            ] = res.data.data;
          }
        }
      });
    },

    // 确定
    handleTrue() {
      return new Promise((resolve, reject) => {
        if (["address", "rowAddress"].includes(this.status)) {
          if (
            this.form.deliveryAreaName === "港澳台" &&
            (!this.form.provinceName || !this.form.cityName)
          ) {
            reject("请选择完整的交货地点");
          }
          if (
            this.form.deliveryAreaName !== "港澳台" &&
            (!this.form.provinceName || !this.form.cityName)
          ) {
            reject("请选择完整的交货地点");
          }
          if (!this.form.deliveryPoints) {
            reject("请填写完整的详细地址");
          }
          resolve();
        } else {
          resolve();
        }
      });
    },

    async confirmSend() {
      try {
        await this.handleTrue();
        this.$emit("ok", this.form);
        this.showDialogVisible = false;
        this.$nextTick(() => {
          this.form = {
            taxRatePercent: "",
            deliveryAreaName: "",
            provinceName: "",
            cityName: "",
            countyName: "",
            deliveryPoints: "",
            deliveryTime: "",
            manufacturer: ""
          };
          this.deliveryAreaOptions = [];
          this.provinceOptions = [];
          this.cityOptions = [];
          this.countyOptions = [];
        });
      } catch (error) {
        this.$showErrorMessage(error);
      }
    }
  },
  computed: {
    ...mapGetters(["getMultiRateCode"])
  }
};
</script>

<style lang="scss" scoped>
#listSettings {
  display: inline-block;
  margin-left: 10px;
  // /deep/ .el-dialog__header {
  // display: flex;
  // align-items: center;
  // }
  /deep/ .revenue-code-number .el-dialog__body {
    width: auto;
    height: auto;
  }
  .el-input,
  .el-textarea {
    width: 260px;
  }
  .area-select {
    & + .area-select {
      margin-left: 10px;
    }
    /deep/ .el-input {
      width: 125px;
    }
  }
}
</style>
